package com.example.loader;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.TranslateAnimation;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.example.loader.utils.Logger;
import com.example.loader.utils.WebViewUtils;
import com.example.loader.view.PageLoader;
import com.example.loader.view.PageLoader.OnFooterRefreshListener;
import com.example.loader.view.PageLoader.OnHeaderRefreshListener;

public class MainActivity extends Activity implements OnHeaderRefreshListener,
		OnFooterRefreshListener, AnimationListener, OnClickListener {
	private static final String	TAG			= "PageLoader";
	PageLoader					loader_main_layout;
	TextView					tv_main_content;
	private WebView				webView;
	private FrameLayout			fl_main_loading;
	private int					mViewHeight;
	private TranslateAnimation	contentDown;
	private TranslateAnimation	contentUp;
	private TranslateAnimation	loadingDown;
	private TranslateAnimation	loadingUp;

	private boolean				bLoad		= true;
	private static boolean		isHeader	= false;
	private static boolean		isFooter	= false;
	private static boolean		isFirst		= true;
	private int					screenHeight;
	private int					statusBarHeight;

	private static String		mUrl;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		initView();
	}

	private void initView() {
		loader_main_layout = (PageLoader) findViewById(R.id.loader_main_layout);
		fl_main_loading = (FrameLayout) findViewById(R.id.fl_main_loading);
		// tv_main_content = (TextView)findViewById(R.id.tv_main_content);
		loader_main_layout.setOnHeaderRefreshListener(this);
		loader_main_layout.setOnFooterRefreshListener(this);

		mBtnPre = (Button) findViewById(R.id.btn_pre_page);
		mBtnNext = (Button) findViewById(R.id.btn_next_page);
		mBtnClear = (Button) findViewById(R.id.btn_clear_cache);
		mBtnExit = (Button) findViewById(R.id.btn_exit_app);
		setListener();

		webView = (WebView) findViewById(R.id.webview);
		WebSettings settings = webView.getSettings();
		settings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

		webView.setWebViewClient(new MyWebViewClient());
		webView.loadUrl(buildUrl(mUrl));

		int modeInt = settings.getCacheMode();
		String cacheMode = null;
		switch (modeInt) {
		case -1:
			cacheMode = "LOAD_DEFAULT";
			break;
		case 0:
			cacheMode = "LOAD_NORMAL";
			break;
		case 1:
			cacheMode = "LOAD_CACHE_ELSE_NETWORK";
			break;
		case 2:
			cacheMode = "LOAD_NO_CACHE";
			break;
		case 3:
			cacheMode = "LOAD_CACHE_ONLY";
			break;
		}
		Logger.e(TAG, "cacheMode = " + cacheMode);
	}

	private void setListener() {
		mBtnPre.setOnClickListener(this);
		mBtnNext.setOnClickListener(this);
		mBtnClear.setOnClickListener(this);
		mBtnExit.setOnClickListener(this);

	}

	@SuppressWarnings("deprecation")
	private void initAnimation() {
		// 获取到当前窗口的高度，用于动画滚动的开始和结束位置
		WindowManager wm = (WindowManager) this
				.getSystemService(WINDOW_SERVICE);
		screenHeight = wm.getDefaultDisplay().getHeight();
		Rect rect = new Rect();
		this.getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
		statusBarHeight = rect.top;
		mViewHeight = screenHeight - statusBarHeight;

		contentDown = new TranslateAnimation(0, 0, 0, mViewHeight);
		contentDown.setDuration(800);
		contentDown.setFillAfter(false);

		contentUp = new TranslateAnimation(0, 0, 0, -mViewHeight);
		contentUp.setDuration(800);
		contentUp.setFillAfter(false);

		loadingDown = new TranslateAnimation(0, 0, -mViewHeight, 0);
		loadingDown.setDuration(800);
		loadingDown.setFillAfter(false);

		loadingUp = new TranslateAnimation(0, 0, mViewHeight, 0);
		loadingUp.setDuration(800);
		loadingUp.setFillAfter(false);

		contentDown.setAnimationListener(this);
		contentUp.setAnimationListener(this);
		loadingDown.setAnimationListener(this);
		loadingUp.setAnimationListener(this);
	}

	@Override
	public void onFooterRefresh(PageLoader view) {
		initAnimation();
		loader_main_layout.postDelayed(new Runnable() {

			@Override
			public void run() {
				isHeader = false;
				isFooter = true;
				if (contentDown != null && contentUp != null
						&& loadingDown != null && loadingUp != null) {
					if (!isFirst) {
						if (isFooter || isHeader) {
							if (isHeader) {
								loader_main_layout.startAnimation(contentDown);
								fl_main_loading.startAnimation(loadingDown);
							} else {
								loader_main_layout.startAnimation(contentUp);
								fl_main_loading.startAnimation(loadingUp);
							}
						}
					}
				} else {
					// 动画对象为null时，不播放动画
					fl_main_loading.setVisibility(View.VISIBLE);
				}
				fl_main_loading.setVisibility(View.VISIBLE);
			}
		}, 0);
	}

	@Override
	public void onHeaderRefresh(PageLoader view) {
		initAnimation();
		loader_main_layout.postDelayed(new Runnable() {

			@Override
			public void run() {
				isHeader = true;
				isFooter = false;
				if (contentDown != null && contentUp != null
						&& loadingDown != null && loadingUp != null) {
					if (!isFirst) {
						if (isFooter || isHeader) {
							if (isHeader) {
								loader_main_layout.startAnimation(contentDown);
								fl_main_loading.startAnimation(loadingDown);
							} else {
								loader_main_layout.startAnimation(contentUp);
								fl_main_loading.startAnimation(loadingUp);
							}
						}
					}
				} else {
					// 动画对象为null时，不播放动画
					fl_main_loading.setVisibility(View.VISIBLE);
				}
			}
		}, 0);

	}

	class MyWebViewClient extends WebViewClient {

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			view.loadUrl(url);
			return super.shouldOverrideUrlLoading(view, url);
		}

		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			super.onPageStarted(view, url, favicon);
			fl_main_loading.setVisibility(View.VISIBLE);
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// webView.setVisibility(View.VISIBLE);
			/*
			 * if (!(contentDown != null && contentUp != null
			 * && loadingDown != null && loadingUp != null)) {
			 * if (isHeader) {// 下拉加载
			 * loader_main_layout.onHeaderRefreshComplete();
			 * } else if (isFooter) {// 上拉加载
			 * loader_main_layout.onFooterRefreshComplete();
			 * }
			 * }
			 */

			if (isHeader) {// 下拉加载
				loader_main_layout.onHeaderRefreshComplete();
			} else if (isFooter) {// 上拉加载
				loader_main_layout.onFooterRefreshComplete();
			}

			webView.postDelayed(new Runnable() {

				@Override
				public void run() {
					fl_main_loading.setVisibility(View.GONE);
				}
			}, 0);

			isFirst = false;
			super.onPageFinished(view, url);
		}
	}

	private static final String	url1	= "http://www.baidu.com";
	private static final String	url2	= "http://www.eoeandroid.com/thread-252572-1-1.html";
	private Button				mBtnPre;
	private Button				mBtnNext;
	private Button				mBtnClear;
	private Button				mBtnExit;

	private String buildUrl(String url) {
		if (null == url || "".equalsIgnoreCase(url)) {
			mUrl = url1;
		} else if (null != url && url1.equalsIgnoreCase(url)) {
			mUrl = url2;
		} else if (null != url && url2.equalsIgnoreCase(url)) {
			mUrl = url1;
		}
		return mUrl;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {
			loader_main_layout.clearAnimation();
			fl_main_loading.clearAnimation();
			webView.goBack();
			return true;
		}
		isFirst = true;
		this.finish();
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onAnimationEnd(Animation animation) {
		if (bLoad) {
			if (isHeader) {// 下拉加载，向上翻页，直接跳转到底部锚点
				webView.loadUrl(buildUrl(mUrl));
				loader_main_layout.onHeaderRefreshComplete();
			} else if (isFooter) {// 上拉加载，不需要跳转到锚点
				webView.loadUrl(buildUrl(mUrl));
				loader_main_layout.onFooterRefreshComplete();
			}
			bLoad = !bLoad;
		} else {
			bLoad = !bLoad;
		}
	}

	@Override
	public void onAnimationRepeat(Animation animation) {

	}

	@Override
	public void onAnimationStart(Animation animation) {

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btn_pre_page:
			webView.loadUrl(buildUrl(mUrl));
			break;
		case R.id.btn_next_page:
			webView.loadUrl(buildUrl(mUrl));
			break;
		case R.id.btn_clear_cache:
			// webView.clearCache(true);
			WebViewUtils.clearCache(getApplicationInfo());
			break;
		case R.id.btn_exit_app:
			this.finish();
			break;
		}
	}
}
